<template>
  <div id="user-view" class="app-container">
    <div class="form-box">
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      />
      <div class="text-right">
        <el-button size="mini" type="primary" @click="update(editData)"
          >确认修改</el-button
        >
      </div>
    </div>
    <!-- <list-search-bar ref="searchbar" :search-rule="searchRule" @submit="getList($event,pageInfo)" @add="showEdit()" @update:value="searchData=$event" /> -->
    <!-- <list-table :showEdit="permissions.edit" @edit="showEdit($event)" @remove="remove" :showRemove="permissions.remove" v-loading="listLoading" :listRule="editRule" :listData="listData" /> -->
    <!-- <pagination :page-sizes="[ 20]" :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNo" :total="pageInfo.total"  @pagination=" getList(searchData,{...pageInfo,pageNo:$event.page})" /> -->
    <back-to-top
      :visibility-height="300"
      :back-position="0"
      transition-name="fade"
    />
  </div>
</template>

<script>
import {
  sysLogin,
  sysEditPwd,
  sysEditPwd as updateApi //更新、新增数据的api
} from "@/api";
import { editRule, searchRule } from "@/formRules/system/UserViewRules";
import { editFormOptions, getData } from "@/formRules";
import cloneDeep from "lodash/cloneDeep";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations.js";
import { mapState } from "vuex";
import { requirementRegexp } from "@/utils/validate";
export default {
  name: "UserView",
  configurations: {
    title: "用户中心",
    icon: "el-icon-s-order",
    isDefault: true,
    show: true,
    num: 1
  },
  data() {
    return {
      editRule: editRule(),
      listData: [],
      searchRule: searchRule(),
      searchData: {}, //搜索表单数据
      editFormInstance: {},
      editData: {},
      editOptions: editFormOptions(),
      editDialog: false,
      editLoading: false,
      listLoading: false,
      pageInfo: {
        pageNo: 1,
        pageSize: 20,
        total: 0,
        pageNum: 0
      },
      permissionList: [] //权限列表
    };
  },
  // 在路由导航进来之前检查权限
  beforeRouteEnter(from, to, next) {
    const permissionList = checkPermission(to.path);
    if (permissionList.length) {
      next(vm => {
        vm.permissionList = permissionList;
      });
      return;
    }
    next({
      name: "403"
    });
  },
  created() {
    console.log(this.userNow);
  },
  mounted() {
    this.editData.userName = this.user.username;
    // this.getList(this.searchData, this.pageInfo);
  },
  computed: {
    // 根据获取的权限列表此处返回各个权限的显示与否
    permissions() {
      return ["edit", "remove", "add"].reduce((pre, cur) => {
        pre[cur] = isDev ? true : this.permissionList.includes(cur);
        return pre;
      }, {});
    },
    ...mapState(["user", "isAdmin", "userNow"])
  },
  methods: {
    /**
     * @name 查询列表
     * @param {Object} query 查询参数，一般为this.searchData
     * @param {Object} pageInfo 页面参数，包括pageSize和pageNo
     * @description 调用成功则刷新listData
     */
    async getList(query, pageInfo) {
      this.listLoading = true;
      const queryParam = {
        ...pageInfo,
        ...query
      };
      const { data } = await searchApi(queryParam).finally(() => {
        this.listLoading = false;
      });

      this.listData = data.dataList;
      delete data.dataList;
      Object.assign(this.pageInfo, data);
    },
    /**
     * @name 编辑表单
     * @param {Object} row 表单数据，新增时为空
     * @description 调用成功打开表单对话框
     */
    showEdit(row) {
      if (!row) {
        this.editData = getData(editRule());
      } else {
        this.editData = cloneDeep(row);
      }
      this.editDialog = true;
    },
    async login(editData) {
      this.$confirm("确认修改当前用户密码?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.update(editData);
        })
        .catch(() => {
          this.$notified({
            message: "已取消删除"
          });
        });
      //   let { data, code, msg } = await sysEditPwd(editData);
      //   if (code == 200) {

      //   } else {
      //     this.$notified.error({
      //       message: msg
      //     });
      //   }
    },
    logout() {
      this.$store.dispatch("logout");
    },
    /**
     * @name 更新数据
     * @param editData 编辑的数据体
     * @description 调用成功关闭对话框并且刷新表单
     */
    async update(editData) {
      if (!this.validation()) return;
      this.editLoading = true;
      let params = {
        // id: this.userNow.id,
        // // userName: editData.userName,
        // userPwd: editData.newPwd
        ...editData
      };
      if (this.editData.surepassword != this.editData.newPwd) {
        this.$notified.error({
          message: "两次输入密码不一致 "
        });
        return false;
      }
      this.$confirm("确认修改当前用户密码?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning"
      })
        .then(async () => {
          const { data, code, msg } = await updateApi(params).finally(
            () => (this.editLoading = false)
          );
          if (code == 200) {
            this.$notify.success({
              message: "密码修改成功,即将重新登录..."
            });

            this.editDialog = false;
            setTimeout(() => {
              this.$nextTick(() => {
                this.logout();
              });
            }, 500);
          } else {
            this.$notified.error({
              message: msg
            });
          }
        })
        .catch(() => {
          this.$notified({
            message: "已取消修改"
          });
        });
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      let satate = false;
      this.editFormInstance.validate((valid, fail) => {
        satate = valid;
      });
      // return true;
      return satate;
    },
    /**
     * @name 删除数据项
     * @description 成功后会刷新列表
     */
    async remove(row) {
      this.listLoading = true;
      const { id } = row;
      const data = await removeApi({ id }).finally(() => {
        this.listLoading = false;
      });

      this.$notify.success({
        message: "删除成功"
      });
      this.getList(this.searchData, this.pageInfo);
    },
    /**
     * @name 重置表单数据
     */
    reset() {
      this?.editFormInstance?.resetFields();
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~element-ui/packages/theme-chalk/src/common/var.scss";
#user-view {
  position: relative;
  overflow: hidden;
  margin-top: 50px;
}
.form-box {
  width: 500px;
}
</style>
